package com.zhida.jiyangcenter.buycar

import android.os.Bundle
import android.print.PrintAttributes
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.marginStart
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.APIShop
import com.zhida.jiyangcenter.api.BaseAPI
import com.zhida.jiyangcenter.api.ShopCarListEntity
import com.zhida.jiyangcenter.mian.BaseActivity
import com.zhida.jiyangcenter.modle.ShopDetailsActivity
import com.zhida.jiyangcenter.order.ConfirmOrderActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.SmoothCheckBox
import kotlinx.android.synthetic.main.activity_buy_car.*

@TitleBar(false)
@ContentLayout(R.layout.activity_buy_car)
class ShopCarActivity : BaseActivity() {
    val adapter = Adapter()
    var money = 0.00
    override fun initConfig(savedInstanceState: Bundle?) {
        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }.title("购物车")
        check_box.setChecked(false, true)
        rv_buy_car.layoutManager = LinearLayoutManager(context)
        rv_buy_car.setSwipeMenuCreator { leftMenu, rightMenu, position ->
            rightMenu.addMenuItem(SwipeMenuItem(context).apply {
                setBackgroundColorResource(R.color.color_333333)
                setTextColorResource(R.color.colorPrimary)
                text = "删除"
                width = dp2px(70f)
                height = ViewGroup.LayoutParams.MATCH_PARENT
            })
        }
        rv_buy_car.setOnItemMenuClickListener { menuBridge, adapterPosition ->
            menuBridge.closeMenu()
            lifecycleScope.request({
                APIShop.service().shopcarDel(adapter.data[adapterPosition].uuid ?: "")
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    adapter.remove(adapterPosition)
                    adapter.notifyDataSetChanged()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })
        }
        rv_buy_car.adapter = adapter
        adapter.setOnItemChildClickListener { _, view, position ->
            var num = adapter.data[position].num
            when (view.id) {
                R.id.tv_item_buy_car_reduce -> {
                    if (adapter.data[position].num > 1) {
                        num--
                        lifecycleScope.request({
                            APIShop.service()
                                .shopcarNumEdit(adapter.data[position]?.uuid ?: "", num)
                        }, object : BaseAPI<Any>() {
                            override fun onSuccess(t: Any?, state: Int, msg: String) {
                                adapter.data[position].num--
                                adapter.notifyItemChanged(position)
                                money -= adapter.data[position].product!!.max_money!!
                                tv_buy_car_money.text = "合计：￥${money}"
                            }

                            override fun onError(e: APIException) {
                                tipFail(e.eMessage)
                            }

                        })
                    } else {
                        toast("太少了，不能再减了")
                    }
                }
                R.id.tv_item_buy_car_add -> {
                    num++
                    lifecycleScope.request({
                        APIShop.service()
                            .shopcarNumEdit(adapter.data[position]?.uuid ?: "", num)
                    }, object : BaseAPI<Any>() {
                        override fun onSuccess(t: Any?, state: Int, msg: String) {
                            adapter.data[position].num++
                            adapter.notifyItemChanged(position)
                            money += adapter.data[position].product!!.max_money!!
                            tv_buy_car_money.text = "合计：￥${money}"
                        }

                        override fun onError(e: APIException) {
                            tipFail(e.eMessage)
                        }
                    })
                }
                R.id.scb_item_buy_car -> {
                    if (adapter.indexList.contains(position)) {
                        adapter.indexList.remove(position)
                        money -= (adapter.data[position].num * adapter.data[position].product!!.max_money!!)
                        tv_buy_car_money.text = "合计：￥${money}"
                    } else {
                        adapter.indexList.add(position)
                        money += (adapter.data[position].num * adapter.data[position].product!!.max_money!!)
                        tv_buy_car_money.text = "合计：￥${money}"
                    }
                    if (adapter.indexList.size == adapter.data.size) {
                        check_box.setChecked(true, true)
                    } else {
                        check_box.setChecked(false, true)
                    }
                    adapter.notifyDataSetChanged()
                }
            }
        }
        adapter.setOnItemClickListener { _, _, position ->
            startActivity<ShopDetailsActivity> {
                putExtra(
                    "uuid",
                    adapter.data[position].product?.uuid
                )
            }
        }
        rv_buy_car.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context)
                .sizeResId(R.dimen.dividerBig).colorResId(R.color.colorBack).build()
        )
        check_box.setOnClickListener {
            if (!check_box.isChecked) {
                check_box.setChecked(!check_box.isChecked, true)
                adapter.indexList.clear()
                adapter.data.forEachIndexed { index, shopCar ->
                    adapter.indexList.add(index)
                    money += (shopCar.num * shopCar.product!!.max_money!!)
                }
                adapter.notifyDataSetChanged()
                tv_buy_car_money.text = "合计：￥${money}"
            }else{
                check_box.setChecked(!check_box.isChecked, true)
                adapter.indexList.clear()
                adapter.notifyDataSetChanged()
                money=0.00
                tv_buy_car_money.text = "合计：￥${money}"
            }
        }
        tv_buy_car_settlement.setOnClickListener {
            if (adapter.indexList.isNullOrEmpty()) {
                toast("请选择要支付的商品")
            } else
                startActivity<ConfirmOrderActivity> {
                    var uuid = ""
                    adapter.indexList.forEach {
                        uuid += if (uuid.isEmpty()) {
                            adapter.data[it]?.uuid
                        } else {
                            "," + adapter.data[it]?.uuid
                        }
                    }
                    putExtra("uuid", uuid)
                    putExtra("type", "ShopCar")
                }
        }
    }

    override fun onResume() {
        super.onResume()
        getData()
    }

    private fun getData() {
        lifecycleScope.request({ APIShop.service().shopcarList() },
            object : BaseAPI<ShopCarListEntity>() {
                override fun onSuccess(t: ShopCarListEntity?, state: Int, msg: String) {
                    adapter.setNewData(t?.shop_car)
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    class Adapter :
        BaseQuickAdapter<ShopCarListEntity.ShopCar, BaseViewHolder>(R.layout.item_item_buy_car) {
        val indexList = ArrayList<Int>()
        override fun convert(helper: BaseViewHolder, item: ShopCarListEntity.ShopCar?) {
            glideImage(helper.getView(R.id.niv_item_buy_car), item?.product?.picture ?: "")
            helper.setText(R.id.tv_item_buy_car_name, item?.product?.name)
                .setText(R.id.tv_item_buy_car_money, "￥" + item?.product?.max_money)
                .setText(R.id.tv_item_buy_car_num, item?.num.toString())
                .setBackgroundRes(R.id.cl_shop_buy_car, R.drawable.bg_store_fill_white8)
                .addOnClickListener(R.id.tv_item_buy_car_reduce)
                .addOnClickListener(R.id.tv_item_buy_car_add)
                .addOnClickListener(R.id.scb_item_buy_car)
            helper.getView<ConstraintLayout>(R.id.cl_shop_buy_car).apply {
                PrintAttributes.Margins(dp2px(16f), 0, dp2px(16f), 0)
            }

            val scb_item_buy_car = helper.getView<SmoothCheckBox>(R.id.scb_item_buy_car)
            scb_item_buy_car.setChecked(
                indexList.contains(helper.layoutPosition - headerLayoutCount),
                true
            )
            helper.addOnClickListener(R.id.scb_item_buy_car)
        }

    }
}